package ar.fi.uba.fallas2;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nlp.NLPExecutor;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import ar.fi.uba.fallas2.business.GuessObject;

public class ActionAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm inForm,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		boolean theEnd=false;
		boolean isFirstQuestion = !SessionHandler.hasQAM(request);
		QuestionAnswerManager qam = SessionHandler.getQAM(request);
		String answer = ((TheOnlyForm) inForm).getAnswer();
		
		boolean answerUnderstood=NLPExecutor.getInstance().interpretar(answer)!=null || isFirstQuestion;
		
		if (answer!=null && answer.length()>0 && answerUnderstood) {
			answer = NLPExecutor.getInstance().interpretar(answer);

			if (!qam.willGuess()) { //no estoy arriesgando
				if (answer!=null) {
					qam.setNextAnswer(answer);
					qam.moveToNextQuestion();
				}
			} else { //estoy arriesgando
				answerUnderstood = answer.equalsIgnoreCase("si") || answer.equalsIgnoreCase("no");
				if (answerUnderstood) {
					//proceso la rta
					if (answer.equalsIgnoreCase("si")) {
						qam.setResponse(qam.getResponse());
						theEnd=true;
					} else {
						//le pifio!
						qam.responseIsWrong();
					}
				}
			}
		}
		

		request.setAttribute("theEnd", new Boolean(theEnd));
		request.setAttribute("answerUnderstood", new Boolean(answerUnderstood));
		request.setAttribute("firstQuestion", new Boolean(isFirstQuestion));
		request.setAttribute("nextQuestion", qam.getNextQuestions());
		request.setAttribute("alreadyAskedQuestions", qam.getAlreadyAskedQuestions());
		request.setAttribute("log", qam.getHTMLLog());
		request.setAttribute("giveUp", new Boolean(qam.willGiveUp()));
		request.setAttribute("guess", new Boolean(qam.willGuess()));
		if (qam.willGuess()) request.setAttribute("response", qam.getResponse());
		
		return mapping.findForward("content1");
	}
}
